<template>
  <div>
    <el-switch
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽"
    />
    <el-button id="matchSave" v-if="draggable" @click="matchSave" size="small`"
      >批量保存</el-button
    >
    <el-button id="matchSave" @click="matchDelete" type="danger" size="small"
      >批量删除</el-button
    >

    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      node-key="catId"
      ref="menuTree"
      :draggable="draggable"
      :allow-drop="allowDrop"
      :default-expanded-keys="expandedKey"
      show-checkbox
      @node-drop="handlerDrop"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            v-if="!node.isLeaf"
            type="text"
            size="mini"
            @click="append(data)"
          >
            Append
          </el-button>
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="remove(node, data)"
          >
            Delete
          </el-button>
          <el-button type="text" size="mini" @click="edit(data)">
            edit
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" auto-complete="off" />
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" auto-complete="off" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span></el-dialog
    >
  </div>
</template>

<script>
export default {
  data() {
    return {
      pCid: [],
      draggable: false,
      updateNodes: [],
      dialogTitle: "",
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      dialogVisible: false,
      category: {
        name: "",
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        catId: null,
        icon: null,
        productUnit: null,
        parentCid: 0,
      },
      dialogType: "",
      maxLevel: 3,
    };
  },
  methods: {
    getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.category;
      });
    },
    allowDrop(draggingNode, dropNode, type) {
      //被拖到的当前节点以及所在父节点总层数不大于3
      // console.log(draggingNode, dropNode, type);

      let deep = this.getNodeLevel(draggingNode);
      if (type === "inner") {
        return deep + dropNode.level <= this.maxLevel;
      }
      return deep + dropNode.parent.level <= this.maxLevel;
    },
    //搜索节点的深度
    getNodeLevel(node) {
      if (node == null) {
        return 0;
      }
      if (node.childNodes == null || node.childNodes.length == 0) {
        return 1;
      }
      let num = 0;
      for (let i = 0; i < node.childNodes.length; i++) {
        let a = this.getNodeLevel(node.childNodes[i]);
        if (a > num) {
          num = a;
        }
      }
      return num + 1;
    },
    //批量保存
    matchSave() {
      this.$http({
        url: this.$http.adornUrl("/product/category/update/sort"),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单顺序修改成功",
          type: "success",
        });
        //刷新菜单
        this.getMenus();
        //展开菜单
        console.log(this.pCid);
        this.expandedKey = this.pCid;
        this.updateNodes = [];
      });
    },
    //批量删除
    matchDelete() {
      let arr = this.$refs.menuTree.getCheckedNodes();
      // console.log(arr);
      this.$confirm("确定要删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = [];
          for (let i = 0; i < arr.length; i++) {
            ids.push(arr[i].catId);
          }
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getMenus();
          });
        })
        .catch(() => {});
    },
    //拖拽成功执行的函数
    handlerDrop(draggingNode, dropNode, type, ev) {
      console.log(draggingNode, dropNode, type, ev);
      //当前节点的最新的父id
      let pCid = 0;
      let siblings = null;
      if (type === "before" || type === "after") {
        pCid = dropNode.parent.data.catId;
        if (pCid == undefined) {
          pCid = 0;
        }
        siblings = dropNode.parent.childNodes;
      } else {
        pCid = dropNode.data.catId;
        siblings = dropNode.childNodes;
      }
      this.pCid.push(pCid);

      //当前拖拽节点的最新顺序
      for (let i = 0; i < siblings.length; i++) {
        //如果当前遍历的是当前拖拽的节点
        if (draggingNode.data.catId === siblings[i].data.catId) {
          let level = draggingNode.level;
          //层级发生变化
          if (level != dropNode.level) {
            level = dropNode.level;
            this.updateChildNodeLevel(draggingNode, level);
          }
          this.updateNodes.push({
            catId: siblings[i].data.catId,
            parentCid: pCid,
            sort: i,
            catLevel: level,
          });
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
        }
      }

      //当前拖拽节点的最新层级
      console.log(this.updateNodes);
    },

    updateChildNodeLevel(node, level) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({
            catId: node.childNodes[i].data.catId,
            catLevel: level + 1,
          });
          this.updateChildNodeLevel(node.childNodes[i], level + 1);
        }
      }
    },
    append(data) {
      console.log(data);
      this.dialogVisible = true;
      this.category.parentCid = data.catId;
      this.category.catLevel = data.catLevel + 1;
      this.category.catId = null;
      this.category.name = "";
      this.category.icon = "";
      this.category.productUnit = "";
      this.dialogType = "add";
      this.dialogTitle = "添加分类";
    },

    edit(data) {
      this.dialogVisible = true;
      this.dialogTitle = "修改分类";
      this.dialogType = "edit";

      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: "get",
      }).then(({ data }) => {
        console.log(data);
        this.category.name = data.data.name;
        this.category.catId = data.data.catId;
        this.category.icon = data.data.icon;
        this.category.productUnit = data.data.productUnit;
        this.category.parentCid = data.data.parentCid;
      });
    },

    remove(node, data) {
      console.log(node, data);

      this.$confirm(`确定要删除【${data.name}】菜单吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let ids = [data.catId];

          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            console.log("删除成功");
            this.$message({
              message: "删除成功！",
              type: "success",
            });
            this.expandedKey = [node.parent.data.catId];
            this.getMenus();
          });
        })
        .catch(() => {});
    },

    //添加三级分类
    addCategory() {
      console.log("要提交的数据", this.category);
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        this.$message({
          message: "添加成功",
          type: "success",
        });
        //刷新菜单
        this.getMenus();
        //关闭对话框
        this.dialogVisible = false;
        //展开菜单
        this.expandedKey = [this.category.parentCid];
      });
    },

    //修改三级分类
    editCategory() {
      let { catId, name, icon, productUnit } = this.category;

      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData({ catId, name, icon, productUnit }, false),
      }).then(({ data }) => {
        this.$message({
          message: "菜单保存成功",
          type: "success",
        });
        //刷新菜单
        this.getMenus();
        //关闭对话框
        this.dialogVisible = false;
        //展开菜单
        this.expandedKey = [this.category.parentCid];
      });
    },

    submitData() {
      if (this.dialogType === "edit") {
        this.editCategory();
      } else {
        this.addCategory();
      }
    },
  },
  created() {
    this.getMenus();
  },
};
</script>

<style>
#matchSave {
  margin-left: 24px;
}
</style>